const router = require('koa-router')()
const response = require('../../config/response')
const mysql = require('../../config/mysql')
const fs = require('fs')
const multer = require('koa-multer')
const PageConfig = require('../../config/page')

const debug = require('../../utils/debug')('API-File')

const upload = multer({
  dest: 'public/file/tmp'
})

fs.exists('public/file/upload', (exists) => {
  if (!exists) {
    fs.mkdir('public/file/upload', (err) => {
      if (err) {
        debug('创建 public/file/upload 失败！')
      } else {
        debug('创建 public/file/upload 成功！')
      }
    })
  }
})
fs.exists('public/file/tmp', (exists) => {
  if (!exists) {
    fs.mkdir('public/file/tmp', (err) => {
      if (err) {
        debug('创建 public/file/tmp 失败！')
      } else {
        debug('创建 public/file/tmp 成功！')
      }
    })
  }
})

router.prefix('/api/file')

const FileType = {
  bmp: 'image/bmp',
  cod: 'image/cis-cod',
  gif: 'image/gif',
  ief: 'image/ief',
  jpe: 'image/jpeg',
  jpeg: 'image/jpeg',
  jpg: 'image/jpeg',
  jfif: 'image/pipeg',
  svg: 'image/svg+xml',
  tif: 'image/tiff',
  tiff: 'image/tiff',
  ras: 'image/x-cmu-raster',
  cmx: 'image/x-cmx',
  ico: 'image/x-icon',
  pnm: 'image/x-portable-anymap',
  pbm: 'image/x-portable-bitmap',
  pgm: 'image/x-portable-graymap',
  ppm: 'image/x-portable-pixmap',
  rgb: 'image/x-rgb',
  xbm: 'image/x-xbitmap',
  xpm: 'image/x-xpixmap',
  xwd: 'image/x-xwindowdump',
  png: 'image/png' ,
  pnz: 'image/png'
}

/**
 * 文件上传
 * {
 *    fieldname: 'file',
 *    originalname: 'baidu.pdf',
 *    encoding: '7bit',
 *    mimetype: 'application/pdf',
 *    destination: 'public/file',
 *    filename: 'f58069de36816c869b107fe3ee435d78',
 *    path: 'public\\file\\f58069de36816c869b107fe3ee435d78',
 *    size: 346072
 * }
 */
router.post('/upload', upload.array('file'), async (ctx) => {
  let files = ctx.req.files
  let sql = ''
  let options =[]
  let urls = []
  console.log(files)
  files.forEach(file => {
    // 复制文件，并删除临时文件
    let ext = file.originalname.substr(file.originalname.lastIndexOf('.'))
    let path = `public/file/upload/${file.filename}${ext}`
    let url = `file/upload/${file.filename}${ext}`
    fs.copyFileSync(file.path, path)
    fs.unlinkSync(file.path)
    options.push(file.originalname, file.filename, path, url, file.mimetype, file.size, ctx.req.body.category ? ctx.req.body.category : 'DEFAULT')
    sql += 'INSERT INTO file(original_name, file_name, path, url, mime_type, size, category) VALUES(?, ?, ?, ?, ?, ?, ?);'
    urls.push(url)
  })
  try {
    await mysql.transaction(sql, options)
    ctx.body = response.success({
      result: urls
    })
  } catch(e) {
    ctx.status = 400
    ctx.body = response.error({
      result: e
    })
  }
})

router.get('/images', async (ctx) => {
  let options = []
  let query = ctx.query
  let size = parseInt(query['size'] || PageConfig.size) // 每页数据量
  let current = parseInt(query['current']) || PageConfig.current // 当前页

  let offet = size * (current - 1) // 数据位移

  let where = ' 1 = 1 '
  let types = query['type']
  if (types && !(types instanceof Array)) {
    types = [types]
  }

  where += 'AND mime_type IN(?)'

  let type = []
  if (types) {
    types.forEach(key => {
      type.push(FileType[key])
    })
  } else {
    for (const key in FileType) {
      if (FileType.hasOwnProperty(key)) {
        type.push(FileType[key])
      }
    }
  }
  // console.log(type)
  options.push(type)

  options.push(offet)
  options.push(size)


  let total = 0 // 总数据量
  let pages = 0 // 总页数

  let result = await mysql.query(`
    SELECT
      (count(*)) total
    FROM
      file
    WHERE
      ${where}
    ORDER BY
      upload_datetime
  `, options)

  total = result.results[0].total // 总数据量
  pages = Math.ceil(total / size) // 总页数

  result = await mysql.query(`
  SELECT
    id,
    category,
    original_name AS originalName,
    file_name AS fileName,
    path,
    url,
    mime_type AS mimeType,
    size,
    upload_datetime AS uploadDatetime
  FROM
    file
  WHERE
    ${where}
  ORDER BY
    upload_datetime
  LIMIT ?,?
  `, options)

  ctx.body = response.success({
    result: {
      list: result.results,
      page: {
        total: total, // 数据量
        current: current, // 当前页数
        size: size, // 页面数据量
        pages: pages // 总共页数
      }
    }
  })
})

module.exports = router
